package com.example.tangjiangxu.photowalldemo;

import android.graphics.Bitmap;
import android.util.Log;
import android.util.LruCache;

/**
 * Created by Administrator on 2017/3/28 0028.
 */
public class ImageCache {
    private static final String TAG = "ImageCache";
    private LruCache<String, Bitmap> mMemoryCache;
    private static ImageCache instance;

    public static ImageCache getInstance() {
        if (instance == null) {
            instance = new ImageCache();
        }
        return instance;
    }

    private ImageCache() {
        //获取到可用内存的最大值，使用内存超出这个值会引起OutOfMemory异常
        //LruCache通过构造函数传入缓存值，以kb为单位
        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        //使用最大可用内存值的1/8作为缓存的大小
        int cacheSize = maxMemory / 8;
        Log.e(TAG, "ImageCache: cacheSize:" + (cacheSize / 1024) + "Mb");
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                Log.e(TAG, "sizeOf: "  + (bitmap.getByteCount() *1.0 / 1024 / 1024) + "Mb");
                //重写此方法来衡量每张图片的大小，不是返回图片数量
                return bitmap.getByteCount() / 1024;
            }
        };
    }

    /**
     * 把bitmap加入到缓存中
     * @param key
     * @param bitmap
     */
    public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (getBitmapFromMemoryCache(key)  == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    /**
     * 从缓存里获得图片
     * @param key
     * @return
     */
    public Bitmap getBitmapFromMemoryCache(String key) {
        return mMemoryCache.get(key);
    }
}
